import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates
import WorkerPCNFirebird

import time
import datetime
import os
import sys
import heartbeating
import pdb

MSLogger.logInit('C:\\safe\\ms.autester.log', 6, True)
MSLogger.logInfo('ms autotester started')
reader = WorkerMSDB.Worker('localhost', '2929', 'PGSMData', 'sa', 'safeinside')
reader.connect()

writer = WorkerPCNFirebird.Worker('192.168.0.121:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')
writer.connect()

if os.path.exists('c:\\safe\\ms.autotester.pid'):
    MSLogger.logError('ms autotester already running')
    sys.exit()

f = open('c:\\safe\\ms.autotester.pid', 'w')
f.close()

cursor = reader.connection.cursor()
wcur = writer.connection.cursor()
td = datetime.timedelta(hours=8)
try:
    lastevents = {}
    while True:
        objects = []
        MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objects)
        MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objects, 'fast')
        for o in objects:
            try:
                query = 'SELECT TOP(1) id,eventTime,type FROM _event_data_internal WHERE deviceId=%s ORDER BY eventTime DESC' % (str(o.objectMSId))
                cursor.execute(query)
                d = cursor.fetchall()
                if len(d) < 1 or len(d[0]) != 3 or (lastevents.has_key(o.objectMSId) and d[0][1] <= lastevents[o.objectMSId]):
                    MSLogger.logError('object(%s:%s) condition fail on: %s' % (str(o.objectPCNId), str(o.objectMSId), str(d)))
                    continue
                if datetime.datetime.fromtimestamp(time.time()) - d[0][1] > td:
                    MSLogger.logError('object(%s:%s) old auto on: %s' % (str(o.objectPCNId), str(o.objectMSId), str(d)))
                    continue
                raw = reader.parseEventPGSM(d[0])
                e = MSData.MSEvent()
                e.fromPGSM_AUTOTEST(raw)
                e.objectId = o.objectPCNId
    
                recId = MSDBTemplates.GET_LastRecId_FROM_sgn(wcur)
                MSDBTemplates.STORE_MSEvent_TO_sgn(wcur, e, recId)
                writer.connection.commit()
                lastevents[o.objectMSId] = e.eventGenerateTime
                MSLogger.logInfo('object(%s:%s) last autotest on %s real %s' % (str(o.objectPCNId), str(o.objectMSId), str(lastevents[o.objectMSId]), str(d[0][1])))
            except Exception, err:
                MSLogger.logError('object(%s:%s) error: %s' % (str(o.objectPCNId), str(o.objectMSId), str(err)))
                continue
            time.sleep(60)
        time.sleep(3600 * 8)
except KeyboardInterrupt:
    MSLogger.logError('ms autotester stopped')
    os.unlink('c:\\safe\\ms.autotester.pid')
except Exception, err:
    MSLogger.logError('ms autotester fatal error: %s' % (str(err)))
    os.unlink('c:\\safe\\ms.autotester.pid')
    
